<template>
	<view class="content">
		<view class="informat">
			<view class="title">商品信息</view>
			<view class="formItem">
				<view class="lab"><text>*</text>商品名称</view>
				<input class="uni-input" v-model.trim="form.name" placeholder="请输入商品名称" placeholder-style="color:#ccc"/>
			</view>
			<view class="formItem">
				<view class="lab"><text>*</text>商品图片</view>
				<view class="photo" @click="uploadPhoto(1)">
					<image :src="domain + form.goods_image" v-if="form.goods_image!=''" mode="scaleToFill" class="img"></image>
					<image src="@/static/image/upload.png" v-else mode="scaleToFill" class="img"></image>
				</view>
			</view>
			<view class="formItem">
				<view class="lab"><text>*</text>轮播图片({{banner_imgs.length}}/3)</view>
				<view class="banners">
					<view class="img" v-for="(img, i) in banner_imgs" :key="i">
						<image :src="domain + img" mode="scaleToFill" class="ima"></image>
					</view>
					<image src="@/static/image/upload.png" v-if="banner_imgs.length < 3" @click="uploadPhoto(2)" mode="scaleToFill" class="img"></image>
				</view>
			</view>
			<view class="formItem">
				<view class="lab"><text>*</text>商品原价</view>
				<input class="uni-input" v-model.trim="form.origin_price" placeholder="请输入商品原价" placeholder-style="color:#ccc"/>
			</view>
			<view class="formItem">
				<view class="lab"><text>*</text>商品售价</view>
				<input class="uni-input" v-model.trim="form.price" placeholder="请输入商品售价" placeholder-style="color:#ccc"/>
			</view>
		</view>
		<view class="informat">
			<view class="title">商品详情描述</view>
			<view class="formItem tags">
				<button type="primary" size="mini" plain class="tag" @click="insertMsg('img')">＋插入图片</button>
				<button type="primary" size="mini" plain class="tag" @click="insertMsg('p')">＋插入段落</button>
			</view>
			<view class="formItem" v-for="(msg, m) in msg_list" :key="m">
				<view class="lab"><text>*</text>{{msg.lab=='p'?'段落描述':'图片描述'}}</view>
				<view class="flex" style="align-items: center;width: 100%;justify-content: flex-end;">
					<textarea placeholder-style="color:#ccc" v-model.trim="msg.val" placeholder="请输入文字描述信息" class="textarea"
						v-if="msg.lab=='p'" style="width: 100%;"/>
					<view class="photo" @click="uploadPhoto(3,msg)" v-else>
						<image :src="domain + msg.val" v-if="msg.val!=''" mode="scaleToFill" class="img"></image>
						<image src="@/static/image/upload.png" v-else mode="scaleToFill" class="img"></image>
					</view>
					<uni-icons type="trash" size="20" color="#ff0000" @click="deleteMsg(m)" class="del ml5"></uni-icons>
				</view>
			</view>
		</view>
		<view class="read">
			<checkbox-group @change="changeChecked">
				<label>
					<checkbox :checked="isChecked" value="1" color="#4EB0FF" style="transform:scale(0.7);position: relative;top: -3rpx;" />
					已阅读并同意
				</label>
			</checkbox-group>
			<text @click="seeAgreement('register')">《商品管理规范》</text>
		</view>
		<button class="primary" @tap="confirmModify()">{{goods_id==0?'上传':'确认'}}</button>
	</view>
</template>

<script>
	import common from '@/static/js/common.js';
	
	export default {
		data() {
			return {
				domain: getApp().globalData.DOMAIN,
				goods_id: 0,
				loading: false,
				isChecked: false,
				ajax_url: '',
				banner_imgs: [],
				msg_list: [],
				form: {
					name: '',
					goods_image: '',
					banner_images: '',
					origin_price: '',
					price: '',
					goods_content: ''
				},
				rules: [
					{name: 'name', rule: 'empty', msg: '商品名称不能为空'},
					{name: 'goods_image', rule: 'empty', msg: '商品图片不能为空'},
					{name: 'origin_price', rule: 'empty', msg: '商品原价不能为空'},
					{name: 'price', rule: 'empty', msg: '商品售价不能为空'},
				],
			}
		},
		onLoad(e) {
			this.goods_id = Number(e.id)
		},
		mounted() {
			if (this.goods_id > 0) {
				this.ajax_url = '/mobile/index/editUserGoods'
				uni.setNavigationBarTitle({title: '商品编辑'})
				let that = this;
				common.api({
					method: 'GET',
					url: '/mobile/index/userGoodsDetail',
					data: {id: that.goods_id},
					success:(res) => {
						if (res.code != 0) {
							uni.showToast({ title: res.msg, icon: 'none' });
							return false;
						}
						that.form.name = res.data.name
						that.form.goods_image = res.data.goods_image
						that.form.origin_price = res.data.origin_price
						that.form.price = res.data.price
						that.banner_imgs = res.data.banner_images.split(',')
						let array = []
						let list = res.data.goods_content.split('<p').filter(item=>item!='').map(item=>'<p'+item)
						list.forEach(item => {
							let itemArr = item.split('<img').filter(it=>it!='').map((it,x)=>(x>0?'<img':'')+it)
							array.push(...itemArr)
						})
						that.msg_list = []
						array.forEach(item => {
							let obj = that.analysisRichText(item)
							if (obj.text.trim() != '') {
								that.msg_list.push({lab: 'p', val: obj.text})
							} else if (obj.images.length > 0) {
								obj.images = obj.images.map(url => url.substr(that.domain.length))
								that.msg_list.push({lab: 'img', val: obj.images[0]})
							}
						})
					}
				});
			} else {
				this.ajax_url = '/mobile/index/addGoods'
				uni.setNavigationBarTitle({title: '商品上传'})
			}
		},
		methods: {
			changeChecked(e) {
				if (e.detail.value.length > 0) {
					this.isChecked = true
				} else {
					this.isChecked = false
				}
			},
			analysisRichText(html) {
			    const text = html.replace(/<[^>]+>/g, ''); // 移除HTML标签，只保留文本内容
			    const imgRegex = /<img\b[^>]+\bsrc="([^"]+)"/gi; // 匹配img标签的src属性
			    const images = [];
			    let match;
			    while ((match = imgRegex.exec(html)) !== null) {
			        images.push(match[1]); // 添加匹配到的图片路径到数组中
			    }
			    return { text, images };
			},
			uploadPhoto(type, item) {
				let that = this;
				uni.chooseImage({
				    count: (type==2?3:1),
				    sourceType: ['album'],
				    success: function (res) {
						for (var i = 0; i < res.tempFilePaths.length; i++) {
							uni.uploadFile({
								url: getApp().globalData.UPLOADURL, 
								filePath: res.tempFilePaths[i],
								header:{
									'token': getApp().globalData.TOKEN
								},
								name: 'file',
								success: (result) => {
									let obj = JSON.parse(result.data);
									if (type == 1) {
										that.form.goods_image = obj.data.url;
									} else if(type == 2) {
										that.banner_imgs.push(obj.data.url)
									} else if(type == 3) {
										item.val = obj.data.url
									}
								}
							});
						}
				    }
				});
			},
			insertMsg(type) {
				this.msg_list.push({lab: type, val: ''})
			},
			deleteMsg(index) {
				this.msg_list = this.msg_list.filter((item,i) => i!=index)
			},
			confirmModify() {
				let that = this;
				if (that.loading) return false;
				let valid = common.validator(that.rules, that.form)
				if (!valid.validator) { uni.showToast({ title: valid.msg, icon: 'none' });return false;}
				if (that.banner_imgs.length==0) { uni.showToast({ title: '轮播图片不能为空', icon: 'none' });return false;}
				that.msg_list = that.msg_list.filter(item=>item.val!='')
				if (that.msg_list.length==0) { uni.showToast({ title: '商品详情描述不能为空', icon: 'none' });return false;}
				if (!that.isChecked) {
					uni.showToast({ title: '请先阅读并勾选商品规范', icon: 'none' });/* 《家朕邦用户协议》 */
					return false
				}
				that.form.goods_content = ''
				that.msg_list.forEach(item => {
					if (item.lab == 'p') {
						that.form.goods_content += '<p style="text-indent:20px">'+item.val+'</p>'
					} else if (item.lab == 'img') {
						that.form.goods_content += '<img src="'+that.domain+item.val+'" style="display:block;margin:10px 0"/>'
					}
				})
				
				that.form.banner_images = that.banner_imgs.join(',')
				if (that.goods_id > 0) {
					that.form.id = that.goods_id
				}
				that.loading = true
				common.api({
					method: 'POST',
					url: that.ajax_url,
					data: that.form,
					success: function(res) {
						that.loading = false
						if (res.code != 0) {
							uni.showToast({ title: res.msg, icon: 'none' });
							return false;
						}
						uni.showToast({ title: (that.goods_id==0?'商品上传':'商品编辑')+'成功', icon: 'success' });
						let pages = getCurrentPages();
						let prevPage = pages[pages.length - 2];
						if (prevPage) {
							uni.navigateBack();
						} else {
							uni.reLaunch({url: '/pages/user/index'})
						}
					},
					error: function () {
						that.loading = false
						uni.showToast({ title: '数据请求异常', icon: 'none' });
					}
				});
			}
		}
	}
</script>

<style lang="less" scoped>
	.content {
		width: 100vw;
		min-height: 100vh;
		position: relative;
		.informat {
			background-color: #fff;
			padding: 0 20rpx;
			margin-bottom: 30rpx;
			.formItem:last-of-type {
				border-bottom: none;
			}
			.title {
				font-weight: bolder;
				font-size: 35rpx;
				padding: 30rpx 16rpx 16rpx;
				border-bottom: 4rpx solid #eee;
			}
			.tags {
				padding: 16rpx 0;
				justify-content: flex-start;
				.tag {
					margin: 0 20rpx 0 0;
					padding: 0 16rpx;
				}
			}
		}
		.read {
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 20rpx;
			color: #999;
			text {
				color: #000;
				position: relative;
				top: -2rpx;
			}
		}
		.primary {
			width: 80vw;
			margin: 60rpx auto 40rpx;
		}
	}
</style>
